from pydantic import BaseModel
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from config import db
import h5py
import json
import shutil

router = APIRouter(default_response_class=JSONResponse)

class Posts(BaseModel):
    symbol: str
    list: list[list[str|int|float]]

@router.post('/support/save')
def save_message(posts: Posts):
    try:
        if posts.symbol:
            # 创建一个数据文件（使用 'a' 模式打开文件，避免覆盖已有内容）
            with h5py.File(db.kline_support, 'a') as f:
                json_str = json.dumps(posts.list)
                f.create_dataset(
                    posts.symbol,
                    data=json_str,
                    dtype=h5py.string_dtype()
                )
                return {
                    'msg': '设置成功',
                    'status': True
                }
        return {
            'msg': '缺少symbol',
            'status': False
        }
    except Exception as e:
        return {
            'msg': f'删除失败: {str(e)}',
            'status': False
        }

@router.get('/support/detail')
def save_message(symbol: str):
    data = []
    try:
        if symbol:
            with h5py.File(db.kline_support, 'a') as f:
                if symbol in f:
                    data_list = f[symbol][()]
                    data = json.loads(data_list.decode('utf-8'))
        return data
    except Exception as e:
        return {
            'msg': f'{str(e)}',
            'status': False
        }

def compact_h5_file(src_path, dst_path, exclude=[]):
    with h5py.File(src_path, 'r') as src, h5py.File(dst_path, 'w') as dst:
        def copy_func(name, obj):
            if any(name.startswith(e) for e in exclude):
                return
            if isinstance(obj, h5py.Dataset):
                src.copy(name, dst)
        src.visititems(copy_func)

@router.get('/support/delete')
def save_message(symbol: str):
    try:
        # 示例：删除 path 数据集
        compact_h5_file(db.kline_support, db.kline_support_copy, exclude=[symbol])
        # 替换原文件
        shutil.move(db.kline_support_copy, db.kline_support)
        return {
            'msg': '删除成功',
            'status': True
        }
    except Exception as e:
        return {
            'msg': f'删除失败: {str(e)}',
            'status': False
        }
